<?php

/**
 * Book
 *
 * @author vbolshov
 */

namespace bs;

use km\db\ActiveRecord;

class Book extends ActiveRecord {
	static protected $table = 'book';
	static protected $defaults = array(
		'title' => null
	);
	static protected $neighbors = array(
		'author' => array('bs\\Author', 'book_author', 'book_id', 'author_id')
	);
	/**
	 * @return Select
	 */
	function getAuthors()
	{
		return parent::getNeighbors('author');
	}
	
	function setAuthors($ids)
	{
		$del = static::getConnection()->prepare("DELETE FROM book_author WHERE book_id = ?");
		$del->execute(array($this->id));
		
		$ins = static::getConnection()->prepare("INSERT INTO book_author (book_id, author_id) VALUES (?, ?)");
		foreach ((array) $ids as $id) {
			$ins->execute(array($this->id, $id));
		}
	}
	
	protected function _createValidator()
	{
		return parent::_createValidator()
			->addRequired('title', 'name is required')
			->addStringRule('title', 'name should be a string');
	}
}